/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AreaListar.java
 *
 * Created on 07/05/2011, 11:01:09 AM
 */
package org.gingresos.regimenimpositivo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import org.gingresosapi.beans.*;
import org.gingresosapi.controller.*;
import org.gingresosapi.generales.Mensajeria;
import org.gingresos.start.MySesion;
import org.jdesktop.swingx.JXTipOfTheDay;
import org.jdesktop.swingx.tips.DefaultTip;
import org.jdesktop.swingx.tips.DefaultTipOfTheDayModel;
import org.jdesktop.swingx.tips.TipOfTheDayModel;

/**
 *
 * @author avbravo
 */
public class CargarRegimenImpositivo extends javax.swing.JInternalFrame {

    Connection conexionIngresos = null;
    String ipIngresos;
    Servidoringresos servidoringresos1;
    ServidoringresosController servidoringresosController1;
    GruporegimenController gruporegimenController1 = new GruporegimenController();
    SubgruporegimenController subgruporegimenController1 = new SubgruporegimenController();
    RegimenController regimenController1 = new RegimenController();
    JXTipOfTheDay tipOfTheDay = new JXTipOfTheDay(loadModel());

    private static TipOfTheDayModel loadModel() {
        List tips = Arrays.asList(new DefaultTip("Tip 1", "Este proceso importa grupo, subgrupo, regimen de la base de datos de ingresos"),
                new DefaultTip("Tip 2", "Este proceso consume mucho tiempo."));
        DefaultTipOfTheDayModel model = new DefaultTipOfTheDayModel(tips);
        return model;
    }
    JLabel statusLabel = new JLabel();

    /** Creates new form AreaListar */
    public CargarRegimenImpositivo() {
        initComponents();


        jXStatusBar1.add(statusLabel);
//        tipOfTheDay.showDialog(null);
        servidoringresos1 = new Servidoringresos();
        servidoringresosController1 = new ServidoringresosController();
        servidoringresos1.setIdmunicipio(MySesion.getIdmunicipio());

        if (servidoringresosController1.findByIdmunicipio(servidoringresos1)) {
            Servidoringresos servidoringresos = servidoringresosController1.getServidoringresoslist().get(0);
            jButtonCargarRegistros.setEnabled(true);

        } else {
            Mensajeria.Mensaje("No se ha establecido el servidor de ingresos");

            jButtonCargarRegistros.setEnabled(false);
        }


    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jXStatusBar1 = new org.jdesktop.swingx.JXStatusBar();
        jButtonCargarRegistros = new javax.swing.JButton();
        jButtonAyuda = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Cargar Regimen Impositivo");

        jLabel2.setText("Esta opción carga al sistema de egresos el regimen impositivo del sistema de ingresos");

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gingresos/resources/gif/return.png"))); // NOI18N
        jButton1.setToolTipText("Cerrar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButtonCargarRegistros.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gingresos/resources/gif/download.png"))); // NOI18N
        jButtonCargarRegistros.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCargarRegistrosActionPerformed(evt);
            }
        });

        jButtonAyuda.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gingresos/resources/gif/help_icon.gif"))); // NOI18N
        jButtonAyuda.setToolTipText("Ayuda");
        jButtonAyuda.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAyudaActionPerformed(evt);
            }
        });

        jLabel1.setText("Nota:");

        jLabel3.setText("Importa las tablas: gruporegimen,subgruporegimen, regimen...");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(68, 68, 68)
                        .addComponent(jButtonCargarRegistros, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonAyuda, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel2))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jXStatusBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 432, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(59, 59, 59)
                        .addComponent(jLabel3)))
                .addContainerGap(45, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jButtonAyuda, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButtonCargarRegistros, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(47, 47, 47)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 70, Short.MAX_VALUE)
                .addComponent(jXStatusBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(34, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
    dispose();
}//GEN-LAST:event_jButton1ActionPerformed

    private void jButtonCargarRegistrosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCargarRegistrosActionPerformed
        Thread queryThread = new Thread() {

            public void run() {
                runQueries();
            }
        };
        queryThread.start();

    }//GEN-LAST:event_jButtonCargarRegistrosActionPerformed

    private void jButtonAyudaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAyudaActionPerformed
        tipOfTheDay.showDialog(this);
    }//GEN-LAST:event_jButtonAyudaActionPerformed
    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            public void run() {
//                try {
//                    new AreaCrear().setVisible(true);
//                } catch (ParseException ex) {
//                    Logger.getLogger(AreaCrear.class.getName()).log(Level.SEVERE, null, ex);
//                }
//            }
//        });
//    }
    private void runQueries() {
        try {
            if (!ConectarIngresos()) {
                Mensajeria.Mensaje("No se pudo conectar...");
                return;
            } else {
                List<Gruporegimen> listGrupoRegimen = new ArrayList<Gruporegimen>();
                String sql = "select * from gruporegimen where activo='si' and idmunicipio='" + MySesion.getIdmunicipio() + "'";
                PreparedStatement psquery = conexionIngresos.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE,
                        ResultSet.CONCUR_UPDATABLE);
                ResultSet rs = psquery.executeQuery();
                rs.next();
                int x = rs.getRow();
                if (x == 0) {
                    Mensajeria.Mensaje("No existen registros en la tabla gruporegimen con esa condicion");
                    rs.close();
                    psquery.close();

                }
                rs.beforeFirst();
                while (rs.next()) {
                    listGrupoRegimen.add(new Gruporegimen(
                            rs.getString("idgruporegimen"), rs.getString("grupo"), rs.getString("observacion"), rs.getDate("fechahora"), MySesion.getUsername(), MySesion.getIdmunicipio(), rs.getString("activo"), "sin definir"));
                }
                rs.close();
                psquery.close();
                if (listGrupoRegimen.size() == 0) {
                    Mensajeria.Mensaje("No existen registros de grupo de regimen");
                }
                /*
                 * subgruporegimen
                 */
                List<Subgruporegimen> listSubgruporegimen = new ArrayList<Subgruporegimen>();
                sql = "select * from subgruporegimen where activo='si' and idmunicipio='" + MySesion.getIdmunicipio() + "'";
                psquery = conexionIngresos.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE,
                        ResultSet.CONCUR_UPDATABLE);
                rs = psquery.executeQuery();
                rs.next();
                x = rs.getRow();
                if (x == 0) {
                    Mensajeria.Mensaje("No existen registros en la tabla subgruporegimencon esa condicion");

                    rs.close();
                    psquery.close();

                }
                rs.beforeFirst();
                while (rs.next()) {
                    listSubgruporegimen.add(new Subgruporegimen(
                            rs.getString("idsubgruporegimen"), rs.getString("idgruporegimen"), rs.getString("subgrupo"), rs.getString("observacion"), MySesion.getUsername(), rs.getDate("fechahora"), MySesion.getIdmunicipio(), rs.getString("activo")));
                }
                rs.close();
                psquery.close();

                if (listSubgruporegimen.size() == 0) {
                    Mensajeria.Mensaje("No hay registros de subgruporegimen");
                }

                /*
                 * Regimen
                 */
                List<Regimen> listRegimen = new ArrayList<Regimen>();
                sql = "select * from regimen where activo='si' and idmunicipio='" + MySesion.getIdmunicipio() + "'";
                psquery = conexionIngresos.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE,
                        ResultSet.CONCUR_UPDATABLE);
                rs = psquery.executeQuery();
                rs.next();
                x = rs.getRow();
                if (x == 0) {
                    Mensajeria.Mensaje("No existen registros en la tabla regimen con esa condicion");
                    rs.close();
                    psquery.close();

                }
                rs.beforeFirst();
                while (rs.next()) {
                    listRegimen.add(new Regimen(
                            rs.getString("idregimen"), rs.getString("idsubgruporegimen"), rs.getString("regimen"), rs.getString("descripcion"), rs.getDouble("valor"), rs.getString("observacion"), MySesion.getUsername(), rs.getDate("fecha"), rs.getDouble("limiteinferior"), rs.getDouble("limitesuperior"), MySesion.getIdmunicipio(), rs.getString("activo")));
                }
                rs.close();
                psquery.close();
                if (listSubgruporegimen.size() == 0) {
                    Mensajeria.Mensaje("No hay registros de regimen");
                }
                conexionIngresos.close();
                /*
                 * Pasar los gruporegimen
                 */
                gruporegimenController1.deleteAll();
                int contador = 0;
                for (Gruporegimen gruporegimen : listGrupoRegimen) {
                    updateProgress("procesando grupo  " + gruporegimen.getIdgruporegimen() + " : " + contador++);
                    if (!gruporegimenController1.exists(gruporegimen)) {
                        if (gruporegimenController1.insert(gruporegimen)) {
                        }
                    }
                }
                /*
                 * Pasar los subgruporegimen
                 */
                contador = 0;
                subgruporegimenController1.deleteAll();
                for (Subgruporegimen subgruporegimen : listSubgruporegimen) {
                    updateProgress("procesando subgrupo  " + subgruporegimen.getIdsubgruporegimen() + " : " + contador++);
                    if (!subgruporegimenController1.exists(subgruporegimen)) {
                        if (subgruporegimenController1.insert(subgruporegimen)) {
                        }
                    }
                }
                /*
                 * Pasar los regimen
                 */
                regimenController1.deleteAll();
                contador = 0;
                for (Regimen regimen : listRegimen) {
                    updateProgress("procesando regimen  " + regimen.getIdregimen() + " : " + contador++);
                    if (!regimenController1.exists(regimen)) {
                        if (regimenController1.insert(regimen)) {
                        }
                    }
                }
                updateProgress("proceso de importacion terminado");
                jButtonCargarRegistros.setEnabled(false);
            }

        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "runQueries()");
        }

    }

    private void updateProgress(final String texto) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                // Here, we can safely update the GUI
                // because we'll be called from the
                // event dispatch thread
//                 statusLabel.setText( texto+ " : " + queryNo);
                statusLabel.setText(texto);
            }
        });
    }

    public Boolean ConectarIngresos() {

        try {
            if (ipIngresos == null || ipIngresos.equals("")) {
                Servidoringresos servidoringresos1 = new Servidoringresos();
                ServidoringresosController servidoringresosController1 = new ServidoringresosController();
                servidoringresos1.setIdmunicipio(MySesion.getIdmunicipio());

                if (servidoringresosController1.findByIdmunicipio(servidoringresos1)) {
                    Servidoringresos servidoringresos = servidoringresosController1.getServidoringresoslist().get(0);
                    this.ipIngresos = servidoringresos.getServidor();
                } else {
                    Mensajeria.Mensaje("No se ha configurado el servidor de ingresos ");
                    return true;
                }
            }


            String databaseDB = "sirmupadb";
            String puertoDB = "3306";
            String userDB = "root";
            String passwordDB = "denver";


            String driver = "org.gjt.mm.mysql.Driver";

            Class.forName(driver).newInstance();
            String url = "jdbc:mysql://" + ipIngresos + ":" + puertoDB + "/" + databaseDB;

            //con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sirmupadb", "root", "denver");
            //con = DriverManager.getConnection(url, "root", "denver");

            conexionIngresos = DriverManager.getConnection(url, userDB, passwordDB);

            if (conexionIngresos == null) {
                Mensajeria.Mensaje("No se pudo establecer la conexion ");

                return false;
            }
            //    Mensajeria.Mensaje("Se conecto exitosamente");
            return true;

        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "Conectar()");
        }
        return null;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButtonAyuda;
    private javax.swing.JButton jButtonCargarRegistros;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private org.jdesktop.swingx.JXStatusBar jXStatusBar1;
    // End of variables declaration//GEN-END:variables
}
